/**
 * Copyright (c) 2009, 2010  Collaborative Development Group, C.S. Dept., University of Bari
 *
 * All rights reserved. This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License v1.0  which accompanies this distribution, and is 
 * available at http://www.eclipse.org/legal/epl-v10.html
 */
package it.uniba.di.cdg.penelope.ui.mvp.databinding;

import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.fieldassist.ControlDecoration;

/**
 * Check that the given object is matching a valid email id. 
 * See http://www.toedter.com/blog/?p=36 .
 */
public class EmailValidator implements IValidator {

	private final ControlDecoration controlDecoration;
	private final String message;

	/**
	 * @param controlDecoration
	 * @param message
	 */
	public EmailValidator( ControlDecoration controlDecoration, String message ) {
		this.controlDecoration = controlDecoration;
		this.message = message;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
	 */
	@Override
	public IStatus validate( Object value ) {
		if (value instanceof String) {
			String email = (String) value;
			if (email.length() == 0) {
				controlDecoration.show();
				return ValidationStatus.error( message );
				//ValidationStatus.error( String.format( "Value %s is not a valid e-mail address.", value ) );
			}
		}
		controlDecoration.hide();
		return Status.OK_STATUS;
	}

}
